/**
 * 后台管理系统纸条的业务逻辑代码
 */

const db = require("../../db/db")
const initModel = require("../../models/init-models")
const { user, scrip, scrip_img } = initModel(db);
const { Op } = require("sequelize");

// 引入删除七牛云的方法
const delQiniu = require("../../comment/delQiniu");

// 关联表关系
user.hasOne(scrip, {
  targetKey: 'id',
  foreignKey: 'user_id',
})
scrip.belongsTo(user, {
  targetKey: 'id',
  foreignKey: 'user_id',
})
// 纸条和纸条图片表关联
scrip.hasMany(scrip_img, {
  targetKey: "id",
  foreignKey: "scrip_id"
})
scrip_img.belongsTo(scrip, {
  targetKey: "id",
  foreignKey: "scrip_id"
})

module.exports = {
  allScrip: async (req, res) => {
    // 获取数据
    let { page, limit, we_chat, content } = req.body
    // 页码和条数
    page = page == null ? 1 : Number(page);
    limit = limit == null ? 5 : Number(limit);

    // 跨越条数
    let offset = (page - 1) * limit;

    let findScrip = null
    // 判断是否要模糊搜索
    if (we_chat != null && content == null) {
      // 根据微信模糊搜索
      findScrip = await scrip.findAndCountAll({
        where: {
          wechat: {
            [Op.like]: `%${we_chat}%`
          }
        },
        include: [
          {
            model: scrip_img,
            attributes: { exclude: ['scrip_id'] },
          },
          user
        ],
        order: [["id", "DESC"]],
        offset,
        limit
      })
    } else if (we_chat == null && content != null) {
      // 根据内容模糊搜索
      findScrip = await scrip.findAndCountAll({
        where: {
          scrip_content: {
            [Op.like]: `%${content}%`
          }
        },
        include: [
          {
            model: scrip_img,
            attributes: { exclude: ['scrip_id'] },
          },
          user
        ],
        order: [["id", "DESC"]],
        offset,
        limit
      })
    } else {
      // 微信号/内容不填或全填都返回全部
      findScrip = await scrip.findAndCountAll({
        include: [
          {
            model: scrip_img,
            attributes: { exclude: ['scrip_id'] },
          },
          user
        ],
        order: [["id", "DESC"]],
        offset,
        limit
      })
    }

    // 返回
    res.send({
      status: 200,
      msg: "获取成功",
      data: {
        count: findScrip.count,
        scrips: findScrip.rows
      }
    })
  },
  // 删除纸条
  delScrip: async (req, res) => {
    // 获取删除纸条id
    let {id} = req.body;
    if(id == null) {
      res.send({
        status: 400,
        msg: "缺少参数"
      });
      return;
    }

    // 查询是否有该纸条
    let findScrip = await scrip.findOne({
      where: {id}
    })
    if(findScrip == null) {
      res.send({
        status: 400,
        msg: "该纸条不存在"
      });
      return;
    }

    // 获取图片数据
    let findScripImg = await scrip_img.findAll({
      where: {scrip_id: id},
      attributes: ["img"]
    })
    // 处理图片  循环删除七牛云图片
    for (const i of findScripImg) {
      i.img = i.img.split("com/")[1];
      await delQiniu(i.img)
    }

    // 删除纸条
    let delResult = await findScrip.destroy();
    // 删除图片
    await scrip_img.destroy({
      where: {scrip_id: id}
    });
   
    if(delResult != null) {
      res.send({
        status: 200,
        msg: "删除成功"
      })
    }
  },
  // 审核纸条
  auditScrip: async (req, res) => {
    // 获取数据
    let { id, audit_type, audit_content} = req.body;
    if(id == null || audit_type == null) {
      res.send({
        status: 400,
        msg: "缺少参数"
      });
      return;
    }
    // 判断传来的值是否合法
    if(audit_type != 3 && audit_type != 2) {
      res.send({
        status: 400,
        msg: "修改不合法",
        error: `audit_type：${audit_type}`
      });
      return
    }
    // 是否存在该纸条
    let findScrip = await scrip.findOne({where: {id}});
    if(findScrip == null) {
      res.send({
        status: 400,
        msg: "该纸条不存在"
      });
      return;
    }
    // 修改
    findScrip.audit = audit_type;
    // 判断是否有不通过原因
    if(audit_content != null) {
      findScrip.audit_content = audit_content;
    }
    let editResult = await findScrip.save();
    if(editResult != null) {
      res.send({
        status: 200,
        msg: "修改成功"
      })
    }
  },
  // 根据审核或未审核返回纸条列表
  auditScripType: async (req, res) => {
    // 获取数据
    let { page, limit, scrip_type } = req.body

    if(scrip_type == null || page == null) {
      res.send({
        status: 400,
        msg: "缺少参数"
      });
      return;
    }

    // 页码和条数
    page = page == null ? 1 : Number(page);
    limit = limit == null ? 5 : Number(limit);
    // 跨越条数
    let offset = (page - 1) * limit;

    // 查找数据
    let allScrip = null;
    if(scrip_type == 1) {
      // 未审核的数据
      allScrip = await scrip.findAndCountAll({
        distinct: true, // 去重不计算 include 的总条数
        where: {
          audit: {
            [Op.in]: [1, 3]
          }
        },
        include: [
          {
            model: scrip_img,
            attributes: { exclude: ['scrip_id'] },
          },
          {
            model: user,
            attributes: {exclude: ["openid"]}
          }
        ],
        order: [["id", "DESC"]],
        offset,
        limit
      })
    } else if(scrip_type != 1) {
      // 已审核的数据
      allScrip = await scrip.findAndCountAll({
        distinct: true, // 去重不计算 include 的总条数
        where: {
          audit: scrip_type
        },
        include: [
          {
            model: scrip_img,
            attributes: { exclude: ['scrip_id'] },
          },
          {
            model: user,
            attributes: {exclude: ["openid"]}
          }
        ],
        order: [["id", "DESC"]],
        offset,
        limit
      })
    }
    // 返回数据
    res.send({
      status: 200,
      msg: "获取成功",
      data: {
        count: allScrip.count,
        scrips: allScrip.rows
      }
    })
  }
}